<template>
  <div class="timestamp-converter">
    <h2>时间戳转换器</h2>
    <div class="section">
      <h3>Unix 时间戳 转 日期</h3>
      <div class="input-group">
        <label for="timestampInput">时间戳 (毫秒)：</label>
        <input id="timestampInput" v-model="timestampInput" type="text" placeholder="例如：1633824000000">
      </div>
      <button @click="convertTimestampToDate">转换为日期</button>
      <p v-if="dateResult"><strong>结果：</strong>{{ dateResult }}</p>
    </div>
    <hr>
    <div class="section">
      <h3>日期 转 Unix 时间戳</h3>
      <div class="input-group">
        <label for="dateInput">日期字符串：</label>
        <input id="dateInput" v-model="dateInput" type="text" placeholder="例如：2021-10-10 12:00:00">
      </div>
      <button @click="convertDateToTimestamp">转换为时间戳</button>
      <p v-if="timestampResult"><strong>结果：</strong>{{ timestampResult }}</p>
    </div>
    <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
  </div>
</template>

<script>
export default {
  name: "TimestampConverter",
  data() {
    return {
      timestampInput: "",
      dateResult: "",
      dateInput: "",
      timestampResult: "",
      errorMessage: ""
    };
  },
  methods: {
    convertTimestampToDate() {
      this.errorMessage = "";
      this.dateResult = "";
      if (!this.timestampInput) {
        this.errorMessage = "请提供时间戳。";
        return;
      }
      const ts = Number(this.timestampInput);
      if (isNaN(ts)) {
        this.errorMessage = "无效的时间戳。";
        return;
      }
      const date = new Date(ts);
      if (isNaN(date.getTime())) {
        this.errorMessage = "无法转换的时间戳。";
        return;
      }
      this.dateResult = date.toLocaleString();
    },
    convertDateToTimestamp() {
      this.errorMessage = "";
      this.timestampResult = "";
      if (!this.dateInput) {
        this.errorMessage = "请提供日期字符串。";
        return;
      }
      const date = new Date(this.dateInput);
      if (isNaN(date.getTime())) {
        this.errorMessage = "无效的日期字符串。";
        return;
      }
      this.timestampResult = date.getTime();
    }
  }
};
</script>

<style scoped>
.timestamp-converter {
  max-width: 600px;
  margin: 20px auto;
  padding: 10px;
}
.section {
  margin-bottom: 20px;
}
.input-group {
  margin: 10px 0;
}
.input-group label {
  display: block;
  margin-bottom: 5px;
}
.input-group input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
button {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 10px;
}
button:hover {
  background-color: #2980b9;
}
.error {
  color: red;
}
</style> 